import os
import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from dotenv import load_dotenv
import requests

# 1. 读取配置
load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '.env'))
QCC_URL = os.getenv('QCC_URL')
print(QCC_URL)

# 2. 启动浏览器，打开登录页
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)  # 登录后不自动关闭
driver = webdriver.Chrome(options=chrome_options)
driver.get(QCC_URL)

print("请在打开的浏览器中手动登录企查查，登录完成后按回车继续...")
input()

# 3. 获取 cookie
cookies = driver.get_cookies()
cookie_dict = {c['name']: c['value'] for c in cookies}
cookie_str = '; '.join([f"{k}={v}" for k, v in cookie_dict.items()])
print("已获取cookie：", cookie_str)

# 4. 拼接请求头
headers = {
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'content-type': 'application/json',
    'origin': 'https://www.qcc.com',
    'referer': 'https://www.qcc.com/web/bigsearch/judicial-litigation/search',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
    # 其他必要header可根据实际情况补充
}
# 某些接口还需要特殊header，比如 x-pid、x-requested-with、06e0fb89a5e9ce060817 等，可以用浏览器F12抓包后补充

# 5. 请求接口
url = 'https://www.qcc.com/api/judicial-litigation/mergeSearch'
data = {
    "searchKey": "342623199211237517",
    "pageSize": 40,
    "pageIndex": 1,
    "mode": 0,
    "isRiskBigData": True,
    "isShowEm": True,
    "isAgg": True,
    "viewType": "card"
}
response = requests.post(url, headers=headers, cookies=cookie_dict, data=json.dumps(data))
print("接口返回：", response.text)

# 6. 关闭浏览器
driver.quit()
